#! python3
# -*- coding: utf-8 -
'''
Created on 2017年05月10日
@author: zxyong 13738196011
'''

import re
import subprocess
from com.zxy.common.Com_Fun import Com_Fun
from com.zxy.interfaceReflect.A01_A1B2C3 import A01_A1B2C3
from com.zxy.z_debug import z_debug
class CHANGE_IP_LINUX(z_debug):
    strResult        = ""
    session_id       = ""
    param_name       = ""
    param_value1     = None
    param_value2     = None
    param_value3     = None
    param_value4     = None
    param_value5     = None
    param_value6     = None
    param_value7     = None
    param_value8     = None
    param_value9     = None
    param_value10    = None
    param_value11     = None  
    param_value12     = None
    param_value13     = None
    param_value14     = None
    param_value15     = None
    param_value16     = None
    param_value17     = None
    param_value18     = None
    param_value19     = None
    param_value20     = None
    strContinue      = "1"
    def __init__(self, params):
        pass
    def init_start(self):        
        if self.param_value6 == "1":
            self.get_ip_info3(self)
        elif self.param_value6 == "2":  
            self.c_ip3(self)        
    def c_ip3(self):        
        if not re.match(r"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$", self.param_value1):
            self.strResult = "{\""+self.param_name+"\": [{\""+Com_Fun.GetLowUpp("s_result")+"\": 0,\""+Com_Fun.GetLowUpp("error_desc")+"\": \"更改IP失败ip地址输入错误\",\""+Com_Fun.GetLowUpp("ip")+"\":\"\",\""+Com_Fun.GetLowUpp("netmask")+"\":\"\",\""+Com_Fun.GetLowUpp("gateway")+"\":\"\",\""+Com_Fun.GetLowUpp("dns")+"\":\"\",\""+Com_Fun.GetLowUpp("mac")+"\":\"\"}]}"               
            self.strContinue = "0"
            pass
        elif not re.match(r"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$", self.param_value3):
            self.strResult = "{\""+self.param_name+"\": [{\""+Com_Fun.GetLowUpp("s_result")+"\": 0,\""+Com_Fun.GetLowUpp("error_desc")+"\": \"更改IP失败网关输入错误\",\""+Com_Fun.GetLowUpp("ip")+"\":\"\",\""+Com_Fun.GetLowUpp("netmask")+"\":\"\",\""+Com_Fun.GetLowUpp("gateway")+"\":\"\",\""+Com_Fun.GetLowUpp("dns")+"\":\"\",\""+Com_Fun.GetLowUpp("mac")+"\":\"\"}]}"               
            self.strContinue = "0"
            pass
        elif not re.match(r"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$", self.param_value4):
            self.strResult = "{\""+self.param_name+"\": [{\""+Com_Fun.GetLowUpp("s_result")+"\": 0,\""+Com_Fun.GetLowUpp("error_desc")+"\": \"更改IP失败DNS输入错误\",\""+Com_Fun.GetLowUpp("ip")+"\":\"\",\""+Com_Fun.GetLowUpp("netmask")+"\":\"\",\""+Com_Fun.GetLowUpp("gateway")+"\":\"\",\""+Com_Fun.GetLowUpp("dns")+"\":\"\",\""+Com_Fun.GetLowUpp("mac")+"\":\"\"}]}"               
            self.strContinue = "0"
            pass
        temPath = "/etc/network/interfaces"
        temFile = None
        temLines = []
        try:
            temFile = open(temPath, "r+")
            temIndex = -1
            while True:
                temLine = temFile.readline()              
                if not temLine:
                    break
                if temLine.find("auto") == 0:
                    temIndex = temIndex + 1
                if temIndex == int(self.param_value5):                        
                    if temLine.find("address") == 0:
                        if self.param_value1 == "":
                            temLines.append("#"+temLine)
                        else:
                            temLines.append("address "+self.param_value1+"\n")
                    elif temLine.find("#address") == 0 and temLine.strip() != "#address" and self.param_value1 != "":
                        temLines.append("address "+self.param_value1+"\n")
                    elif temLine.find("gateway") == 0:
                        if self.param_value3 == "":
                            temLines.append("#"+temLine)
                        else:
                            temLines.append("gateway "+self.param_value3+"\n")
                    elif temLine.find("#gateway") == 0 and temLine.strip() != "#gateway" and self.param_value3 != "":
                        temLines.append("gateway "+self.param_value3+"\n")
                    elif temLine.find("dns") == 0:
                        if self.param_value4 == "":
                            temLines.append("#"+temLine)
                        else:
                            temLines.append("dns "+self.param_value4+"\n")
                    elif temLine.find("#dns") == 0 and temLine.strip() != "#dns" and self.param_value4 != "":
                        temLines.append("dns "+self.param_value4+"\n")
                    elif temLine.find("netmask") == 0:                        
                        if self.param_value2 == "":
                            temLines.append("#"+temLine)
                        else:
                            temLines.append("netmask "+self.param_value2+"\n")
                    elif temLine.find("#netmask") == 0 and temLine.strip() != "#netmask" and self.param_value2 != "":
                        temLines.append("netmask "+self.param_value2+"\n")
                    else:                    
                        temLines.append(temLine)
                else:
                    temLines.append(temLine)
            self.strResult = "{\""+self.param_name+"\": [{\""+Com_Fun.GetLowUpp("s_result")+"\": 1,\""+Com_Fun.GetLowUpp("error_desc")+"\": \"更改IP成功\",\""+Com_Fun.GetLowUpp("ip")+"\":\"\",\""+Com_Fun.GetLowUpp("netmask")+"\":\"\",\""+Com_Fun.GetLowUpp("gateway")+"\":\"\",\""+Com_Fun.GetLowUpp("dns")+"\":\"\",\""+Com_Fun.GetLowUpp("mac")+"\":\"\"}]}"               
            self.strContinue = "0"
            temFile.seek(0,0)
            temFile.writelines(temLines)
            temFile.truncate()
            temFile.close()
            aa = A01_A1B2C3()
            aa.param_value2 = "/etc/init.d/networking restart"
            aa.CmdExecLinux()
        except Exception as e:
            self.strResult = "{\""+self.param_name+"\": [{\""+Com_Fun.GetLowUpp("s_result")+"\": 0,\""+Com_Fun.GetLowUpp("error_desc")+"\": \"获取IP失败"+Com_Fun.py_urlencode(repr(e))+"\",\""+Com_Fun.GetLowUpp("ip")+"\":\"\",\""+Com_Fun.GetLowUpp("netmask")+"\":\"\",\""+Com_Fun.GetLowUpp("gateway")+"\":\"\",\""+Com_Fun.GetLowUpp("dns")+"\":\"\",\""+Com_Fun.GetLowUpp("mac")+"\":\"\"}]}"
            self.strContinue = "0" 
        finally:
            pass
    def c_ip2(self):
        if not re.match(r"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$", self.param_value1):
            self.strResult = "{\""+self.param_name+"\": [{\""+Com_Fun.GetLowUpp("s_result")+"\": 0,\""+Com_Fun.GetLowUpp("error_desc")+"\": \"更改IP失败ip地址输入错误\",\""+Com_Fun.GetLowUpp("ip")+"\":\"\",\""+Com_Fun.GetLowUpp("netmask")+"\":\"\",\""+Com_Fun.GetLowUpp("gateway")+"\":\"\",\""+Com_Fun.GetLowUpp("dns")+"\":\"\",\""+Com_Fun.GetLowUpp("mac")+"\":\"\"}]}"               
            self.strContinue = "0"
            pass
        elif not re.match(r"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$", self.param_value3):
            self.strResult = "{\""+self.param_name+"\": [{\""+Com_Fun.GetLowUpp("s_result")+"\": 0,\""+Com_Fun.GetLowUpp("error_desc")+"\": \"更改IP失败网关输入错误\",\""+Com_Fun.GetLowUpp("ip")+"\":\"\",\""+Com_Fun.GetLowUpp("netmask")+"\":\"\",\""+Com_Fun.GetLowUpp("gateway")+"\":\"\",\""+Com_Fun.GetLowUpp("dns")+"\":\"\",\""+Com_Fun.GetLowUpp("mac")+"\":\"\"}]}"               
            self.strContinue = "0"
            pass
        elif not re.match(r"^(?:[0-9]{1,3}\.){3}[0-9]{1,3}$", self.param_value4):
            self.strResult = "{\""+self.param_name+"\": [{\""+Com_Fun.GetLowUpp("s_result")+"\": 0,\""+Com_Fun.GetLowUpp("error_desc")+"\": \"更改IP失败DNS输入错误\",\""+Com_Fun.GetLowUpp("ip")+"\":\"\",\""+Com_Fun.GetLowUpp("netmask")+"\":\"\",\""+Com_Fun.GetLowUpp("gateway")+"\":\"\",\""+Com_Fun.GetLowUpp("dns")+"\":\"\",\""+Com_Fun.GetLowUpp("mac")+"\":\"\"}]}"               
            self.strContinue = "0"
            pass
        temPath = "/etc/sysconfig/network-scripts/ifcfg-eth"+str(int(self.param_value5) - 1)
        temFile = None
        temLines = []
        try:
            temFile = open(temPath, "r+")
            while True:
                temLine = temFile.readline()              
                if not temLine:
                    break
                if temLine.find("IPADDR=") != -1:
                    temLines.append("IPADDR="+self.param_value1+"\n")
                elif temLine.find("GATEWAY=") != -1:
                    temLines.append("GATEWAY="+self.param_value3+"\n")
                elif temLine.find("DNS1=") != -1:
                    temLines.append("DNS1="+self.param_value4+"\n")
                else:                    
                    temLines.append(temLine)
            self.strResult = "{\""+self.param_name+"\": [{\""+Com_Fun.GetLowUpp("s_result")+"\": 1,\""+Com_Fun.GetLowUpp("error_desc")+"\": \"更改IP成功\",\""+Com_Fun.GetLowUpp("ip")+"\":\"\",\""+Com_Fun.GetLowUpp("netmask")+"\":\"\",\""+Com_Fun.GetLowUpp("gateway")+"\":\"\",\""+Com_Fun.GetLowUpp("dns")+"\":\"\",\""+Com_Fun.GetLowUpp("mac")+"\":\"\"}]}"               
            self.strContinue = "0"
            temFile.seek(0,0)
            temFile.writelines(temLines)
            temFile.truncate()
            temFile.close()
            aa = A01_A1B2C3()
            aa.param_value2 = "service network restart"
            aa.CmdExecLinux()
        except Exception as e:
            self.strResult = "{\""+self.param_name+"\": [{\""+Com_Fun.GetLowUpp("s_result")+"\": 0,\""+Com_Fun.GetLowUpp("error_desc")+"\": \"获取IP失败"+Com_Fun.py_urlencode(repr(e))+"\",\""+Com_Fun.GetLowUpp("ip")+"\":\"\",\""+Com_Fun.GetLowUpp("netmask")+"\":\"\",\""+Com_Fun.GetLowUpp("gateway")+"\":\"\",\""+Com_Fun.GetLowUpp("dns")+"\":\"\",\""+Com_Fun.GetLowUpp("mac")+"\":\"\"}]}"
            self.strContinue = "0" 
        finally:
            pass
    def get_ip_info3(self):
        temPath = "/etc/network/interfaces"
        temFile = None
        temLines = []            
        self.strResult = "{\""+self.param_name+"\": [{\""+Com_Fun.GetLowUpp("s_result")+"\": 1,\""+Com_Fun.GetLowUpp("error_desc")+"\": \"获取IP成功\""
        try:
            temFile = open(temPath, "r+")
            temIndex = -1
            while True:
                temLine = temFile.readline()              
                if not temLine:
                    break
                temLine = temLine.strip()
                temLines.append(temLine) # 整行读取数据
                if temLine.find("auto") == 0:
                    temIndex = temIndex + 1
                if temIndex == int(self.param_value5):
                    if temLine.find("address") == 0:
                        self.param_value1 = temLine.split(" ")[1]
                    elif temLine.find("gateway") == 0:
                        self.param_value3 = temLine.split(" ")[1]
                    elif temLine.find("dns") == 0:
                        self.param_value4 = temLine.split(" ")[1]
                    elif temLine.find("netmask") == 0:
                        self.param_value2 = temLine.split(" ")[1]  
            self.strResult = self.strResult +",\""+Com_Fun.GetLowUpp("ip")+"\":\""+self.param_value1+"\""
            self.strResult = self.strResult +",\""+Com_Fun.GetLowUpp("netmask")+"\":\""+self.param_value2+"\""
            self.strResult = self.strResult +",\""+Com_Fun.GetLowUpp("gateway")+"\":\""+self.param_value3+"\""
            self.strResult = self.strResult +",\""+Com_Fun.GetLowUpp("dns")+"\":\""+self.param_value4+"\""
            self.strResult = self.strResult +",\""+Com_Fun.GetLowUpp("mac")+"\":\""+Com_Fun.GetMacAddr()+"\""
            self.strResult = self.strResult + "}]}"
            self.strContinue = "0"
            temFile.close()           
        except Exception as e:
            self.strResult = "{\""+self.param_name+"\": [{\""+Com_Fun.GetLowUpp("s_result")+"\": 0,\""+Com_Fun.GetLowUpp("error_desc")+"\": \"获取IP失败"+Com_Fun.py_urlencode(repr(e))+"\",\""+Com_Fun.GetLowUpp("ip")+"\":\"\",\""+Com_Fun.GetLowUpp("netmask")+"\":\"\",\""+Com_Fun.GetLowUpp("gateway")+"\":\"\",\""+Com_Fun.GetLowUpp("dns")+"\":\"\",\""+Com_Fun.GetLowUpp("mac")+"\":\"\"}]}"
            self.strContinue = "0" 
        finally:
            pass
    def get_ip_info2(self):
        temPath = "/etc/sysconfig/network-scripts/ifcfg-eth"+str(int(self.param_value5) - 1)
        temFile = None
        temLines = []            
        self.strResult = "{\""+self.param_name+"\": [{\""+Com_Fun.GetLowUpp("s_result")+"\": 1,\""+Com_Fun.GetLowUpp("error_desc")+"\": \"获取IP成功\""
        try:
            temFile = open(temPath, "r+")
            while True:
                temLine = temFile.readline()              
                if not temLine:
                    break
                temLine = temLine.strip()
                temLines.append(temLine) # 整行读取数据
                if temLine.find("IPADDR=") != -1:
                    self.param_value1 = temLine[temLine.find("IPADDR=")+7:len(temLine)]
                elif temLine.find("GATEWAY=") != -1:
                    self.param_value3 = temLine[temLine.find("GATEWAY=")+8:len(temLine)]
                elif temLine.find("DNS1=") != -1:
                    self.param_value4 = temLine[temLine.find("DNS1=")+5:len(temLine)]
                elif temLine.find("HWADDR=") != -1:
                    self.param_value5 = temLine[temLine.find("HWADDR=")+7:len(temLine)]  
            self.strResult = self.strResult +",\""+Com_Fun.GetLowUpp("ip")+"\":\""+self.param_value1+"\""
            self.strResult = self.strResult +",\""+Com_Fun.GetLowUpp("netmask")+"\":\"255.255.255.0\""
            self.strResult = self.strResult +",\""+Com_Fun.GetLowUpp("gateway")+"\":\""+self.param_value3+"\""
            self.strResult = self.strResult +",\""+Com_Fun.GetLowUpp("dns")+"\":\""+self.param_value4+"\""
            self.strResult = self.strResult +",\""+Com_Fun.GetLowUpp("mac")+"\":\""+self.param_value5+"\""
            self.strResult = self.strResult + "}]}"
            self.strContinue = "0"
            temFile.close()           
        except Exception as e:
            self.strResult = "{\""+self.param_name+"\": [{\""+Com_Fun.GetLowUpp("s_result")+"\": 0,\""+Com_Fun.GetLowUpp("error_desc")+"\": \"获取IP失败"+Com_Fun.py_urlencode(repr(e))+"\",\""+Com_Fun.GetLowUpp("ip")+"\":\"\",\""+Com_Fun.GetLowUpp("netmask")+"\":\"\",\""+Com_Fun.GetLowUpp("gateway")+"\":\"\",\""+Com_Fun.GetLowUpp("dns")+"\":\"\",\""+Com_Fun.GetLowUpp("mac")+"\":\"\"}]}"
            self.strContinue = "0" 
        finally:
            pass
    def find_all_ip(self,platform):
        ipstr = '([0-9]{1,3}\.){3}[0-9]{1,3}'
        if platform == "Darwin" or platform == "Linux":
            ipconfig_process = subprocess.Popen("ifconfig", stdout=subprocess.PIPE)
            output = ipconfig_process.stdout.read()
            ip_pattern = re.compile('(inet %s)' % ipstr)
            if platform == "Linux":
                ip_pattern = re.compile('(inet addr:%s)' % ipstr)
            pattern = re.compile(ipstr)
            iplist = []
            for ipaddr in re.finditer(ip_pattern, str(output)):
                ip = pattern.search(ipaddr.group())
                if ip.group() != "127.0.0.1":
                    iplist.append(ip.group())
            return iplist
        elif platform == "Windows":
            ipconfig_process = subprocess.Popen("ipconfig", stdout=subprocess.PIPE)
            output = ipconfig_process.stdout.read()
            ip_pattern = re.compile("IPv4 Address(\. )*: %s" % ipstr)
            pattern = re.compile(ipstr)
            iplist = []
            for ipaddr in re.finditer(ip_pattern, str(output)):
                ip = pattern.search(ipaddr.group())
                if ip.group() != "127.0.0.1":
                    iplist.append(ip.group())
            return iplist
    def find_all_mask(self,platform):
        ipstr = '([0-9]{1,3}\.){3}[0-9]{1,3}'
        maskstr = '0x([0-9a-f]{8})'
        if platform == "Darwin" or platform == "Linux":
            ipconfig_process = subprocess.Popen("ifconfig", stdout=subprocess.PIPE)
            output = ipconfig_process.stdout.read()
            mask_pattern = re.compile('(netmask %s)' % maskstr)
            pattern = re.compile(maskstr)
            if platform == "Linux":
                mask_pattern = re.compile(r'Mask:%s' % ipstr)
                pattern = re.compile(ipstr)
            masklist = []
            for maskaddr in mask_pattern.finditer(str(output)):
                mask = pattern.search(maskaddr.group())
                if mask.group() != '0xff000000' and mask.group() != '255.0.0.0':
                    masklist.append(mask.group())
            return masklist
        elif platform == "Windows":
            ipconfig_process = subprocess.Popen("ipconfig", stdout=subprocess.PIPE)
            output = ipconfig_process.stdout.read()
            mask_pattern = re.compile(r"Subnet Mask (\. )*: %s" % ipstr)
            pattern = re.compile(ipstr)
            masklist = []
            for maskaddr in mask_pattern.finditer(str(output)):
                mask = pattern.search(maskaddr.group())
                if mask.group() != '255.0.0.0':
                    masklist.append(mask.group())
            return masklist
    def get_broad_addr(self,ipstr, maskstr):
        iptokens = map(int, ipstr.split("."))
        masktokens = map(int, maskstr.split("."))
        broadlist = []
        for i in range(len(iptokens)):
            ip = iptokens[i]
            mask = masktokens[i]
            broad = ip & mask | (~mask & 255)
            broadlist.append(broad)
        return '.'.join(map(str, broadlist))
    def find_all_broad(self,platform):
        ipstr = '([0-9]{1,3}\.){3}[0-9]{1,3}'
        if platform == "Darwin" or platform == "Linux":
            ipconfig_process = subprocess.Popen("ifconfig", stdout=subprocess.PIPE)
            output = (ipconfig_process.stdout.read())
            broad_pattern = re.compile('(broadcast %s)' % ipstr)
            if platform == "Linux":
                broad_pattern = re.compile(r'Bcast:%s' % ipstr)
            pattern = re.compile(ipstr)
            broadlist = []
            for broadaddr in broad_pattern.finditer(str(output)):
                broad = pattern.search(broadaddr.group())
                broadlist.append(broad.group())
            return broadlist
        elif platform == "Windows":
            iplist = self.find_all_ip(platform)
            masklist = self.find_all_mask(self,platform)
            broadlist = []
            for i in range(len(iplist)):
                broadlist.append(self.get_broad_addr(self,iplist[i], masklist[i]))
            return broadlist